<template>
  <div class="app-container">
    <el-tabs tab-position="top" :value="processed === true ? 'approval' : 'form'" id="pdfDom" style="padding:10px">

      <el-tab-pane label="任务办理" name="approval" v-if="processed === true">
        <!-- <el-card class="box-card card" shadow="never">
          <div slot="header" class="clearfix card-header">
            <span>工单轨迹</span>
          </div>
          <el-steps :active="historyProcNodeList.length - 1" finish-status='success' align-center>
            <el-step v-for="(item, index) in historyProcNodeList" :key="index" :title="item.activityName"
              :description="apendStr(item.assigneeName, item.endTime)" />
          </el-steps>
        </el-card> -->
        <div v-if="formOpen">
          <el-card class="box-card card" shadow="never" v-for="(formInfo, index) in processFormList" :key="index">
            <!-- <div slot="header" class="clearfix card-header">
              <span>{{ `【${formInfo.title}】` }}</span>
              <span v-if="formInfo.assigneeName" >{{`&nbsp;实际办理：` }}</span>
              <span v-if="formInfo.assigneeName" style="font-weight:normal">{{`${formInfo.assigneeName}` }}</span>
              <span v-if="formInfo.endTime" >{{`&nbsp;办结时间：` }}</span>
              <span v-if="formInfo.endTime" style="font-weight:normal">{{`${formInfo.endTime}` }}</span>
            </div> -->
            <!--流程处理表单模块-->
            <!-- <parser :form-conf="formInfo" /> -->
            <parser :key="new Date().getTime()"  :form-conf="formInfo" v-if="formInfo.formRef" />
            <CptSelfForm :ref="'CptSelfFormView'+index" :formDataCfg="getSelfFormData(formInfo)" :isView="true"  :isDisable="true" :isFreezed="true" v-else></CptSelfForm>
          </el-card>
        </div>
        <el-card class="box-card card" shadow="never">
          <div slot="header" class="clearfix card-header">
            <span>审批工单</span>
            <span v-if="historyProcNodeList && historyProcNodeList.length" style="font-weight:normal">&nbsp;当前处理节点：{{`${historyProcNodeList[historyProcNodeList.length - 1].activityName}` }}</span>            
          </div>
          <el-row :gutter="10" type="flex" justify="center">
            <el-col :span="1.5" >
              <el-tooltip content="重新分配" placement="top">
                <el-button icon="el-icon-thumb" type="success" @click="handleTransfer" round class="operate-btn">重新分配</el-button>
              </el-tooltip>
            </el-col>
            <el-col :span="1.5" >
              <el-tooltip content="撤销" placement="top">
                <el-button icon="el-icon-circle-close" type="danger" @click="handleCancel" round class="operate-btn">撤销</el-button>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20" :offset="2">
              <el-form ref="taskForm" :model="taskForm" :rules="rules" label-width="120px">
                <el-form-item label="备注" prop="comment">
                  <el-input type="textarea" :rows="5" v-model="taskForm.comment" placeholder="请输入审批意见" />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card card" shadow="never">
          <div slot="header" class="clearfix card-header">
            <span>流转记录</span>
          </div>
          <el-col :span="20" :offset="2">
            <div class="block">
              <el-timeline>
                <el-timeline-item v-for="(item, index) in historyProcNodeList" :key="index" :icon="setIcon(item.endTime)"
                  :color="setColor(item.endTime)">
                  <p style="font-weight: 700">{{ item.activityName }}</p>
                  <el-card v-if="item.activityType === 'startEvent'" class="box-card" shadow="hover">
                    {{ item.assigneeName }} 在 {{ item.createTime }} 发起工单
                  </el-card>
                  <el-card v-if="item.activityType === 'userTask'" class="box-card" shadow="hover">
                    <el-descriptions :column="5" :labelStyle="{ 'font-weight': 'bold' }" v-if="!item.commentList || !item.commentList.length">
                      <!-- <el-descriptions-item label="接收时间">{{ item.createTime || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="实际办理">{{ item.assigneeName || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="候选办理">{{ item.candidate || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="办结时间">{{ item.endTime || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="耗时">{{ item.duration || '-' }}</el-descriptions-item> -->
                      <el-descriptions-item label="应办人员">{{ item.assigneeName || item.candidate || '-' }}</el-descriptions-item>
                    </el-descriptions>
                    <div v-if="item.commentList && item.commentList.length > 0">
                      <div v-for="(comment, commentIndex) in filterRepetitionCommentInfo(item.commentList)" :key="commentIndex">
                        <el-divider content-position="left" v-if="isShowCommentInfo(comment)">
                          <span>{{ comment.userId }}</span>
                          <el-tag :type="approveTypeTag(comment.type)" size="mini">{{ (index === 1 && comment.type === '1') ? '发起申请' : commentType(comment.type)
                          }}</el-tag>
                          <el-tag type="info" effect="plain" size="mini">{{ comment.time }}</el-tag>
                        </el-divider>
                        <span>{{ comment.fullMessage }}</span>
                      </div>
                    </div>
                  </el-card>
                  <el-card v-if="item.activityType === 'endEvent'" class="box-card" shadow="hover">
                    {{ item.createTime }} 结束工单
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-col>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="工单信息" name="form" id="pdfDom" v-else>
        <el-button size="small" type="text" @click="getPdf()" style="float: right; margin-right: 60px; font-size: 16px;">
          PDF导出
        </el-button>
        <!-- <el-card shadow="never" class="card">
          <div slot="header" class="clearfix card-header">
            <span>工单轨迹</span>
          </div>
          <el-steps :active="historyProcNodeList.length - 1" finish-status='success' align-center>
            <el-step v-for="(item, index) in historyProcNodeList" :key="index" :title="item.activityName"
              :description="apendStr(item.assigneeName, item.endTime)" />
          </el-steps>
        </el-card> -->
        <div v-if="formOpen">
          <el-card class="card" shadow="never" v-for="(formInfo, index) in processFormList" :key="index">
            <!-- <div slot="header" class="clearfix card-header">
              <span>{{ `【${formInfo.title}】` }}</span>
              <span v-if="formInfo.assigneeName" >{{`&nbsp;实际办理：` }}</span>
              <span v-if="formInfo.assigneeName" style="font-weight:normal">{{`${formInfo.assigneeName}` }}</span>
              <span v-if="formInfo.endTime" >{{`&nbsp;办结时间：` }}</span>
              <span v-if="formInfo.endTime" style="font-weight:normal">{{`${formInfo.endTime}` }}</span>
            </div> -->
            <!--流程处理表单模块-->
            <CptSelfForm :ref="'CptSelfFormView2'+index" :formDataCfg="getSelfFormData(formInfo)" :isView="true"  :isDisable="true" :isFreezed="true"></CptSelfForm>
          </el-card>
        </div>
        <el-card class="box-card card" shadow="never">
          <div slot="header" class="clearfix card-header">
            <span>流转记录</span>
          </div>
          <el-col :span="20" :offset="2">
            <div class="block">
              <el-timeline>
                <el-timeline-item v-for="(item, index) in historyProcNodeList" :key="index" :icon="setIcon(item.endTime)"
                  :color="setColor(item.endTime)">
                  <p style="font-weight: 700">{{ item.activityName }}</p>
                  <el-card v-if="item.activityType === 'startEvent'" class="box-card" shadow="hover">
                    {{ item.assigneeName }} 在 {{ item.createTime }} 发起工单
                  </el-card>
                  <el-card v-if="item.activityType === 'userTask'" class="box-card" shadow="hover">
                    <el-descriptions :column="5" :labelStyle="{ 'font-weight': 'bold' }" v-if="!item.commentList || !item.commentList.length">
                      <!-- <el-descriptions-item label="接收时间">{{ item.createTime || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="实际办理">{{ item.assigneeName || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="候选办理">{{ item.candidate || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="办结时间">{{ item.endTime || '-' }}</el-descriptions-item> -->
                      <!-- <el-descriptions-item label="耗时">{{ item.duration || '-' }}</el-descriptions-item> -->
                      <el-descriptions-item label="应办人员">{{ item.assigneeName || item.candidate || '-' }}</el-descriptions-item>
                    </el-descriptions>
                    <div v-if="item.commentList && item.commentList.length > 0">
                      <div v-for="(comment, commentIndex) in filterRepetitionCommentInfo(item.commentList)" :key="commentIndex">
                        <el-divider content-position="left" v-if="isShowCommentInfo(comment)">
                          <span>{{ comment.userId }}</span>
                          <el-tag :type="approveTypeTag(comment.type)" size="mini">{{ (index === 1 && comment.type === '1') ? '发起申请' : commentType(comment.type)
                          }}</el-tag>
                          <el-tag type="info" effect="plain" size="mini">{{ comment.time }}</el-tag>
                        </el-divider>
                        <span>{{ comment.fullMessage }}</span>
                      </div>
                    </div>
                  </el-card>
                  <el-card v-if="item.activityType === 'endEvent'" class="box-card" shadow="hover">
                    {{ item.createTime }} 结束工单
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-col>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="工单跟踪" name="track">
        <el-card class="box-card card" shadow="never">
          <process-viewer :key="`designer-${loadIndex}`" :style="'height:' + height" :xml="xmlData"
            :finishedInfo="finishedInfo" :allCommentList="historyProcNodeList" />
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!--退回流程-->
    <el-dialog :title="returnTitle" :visible.sync="returnOpen" width="40%" append-to-body>
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item label="退回节点" prop="targetKey">
          <el-radio-group v-model="taskForm.targetKey">
            <el-radio-button v-for="item in returnTaskList" :key="item.id" :label="item.id">{{ item.name
            }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="returnOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitReturn">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="userData.title" :visible.sync="userData.open" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--机构数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>机构列表</span>
            </div>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入机构名称" clearable size="small" prefix-icon="el-icon-search" />
              <el-tree :data="deptOptions" :props="deptProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" highlight-current node-key="id" />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <!-- 查询条件 -->
          <el-form :model="queryParams" ref="userQueryForm" size="small" :inline="true" v-show="true" label-width="68px">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入用户昵称"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <!-- 查询结果 -->
          <el-table ref="userTable" :key="userData.type" height="500" v-loading="userLoading" :data="userList"
            highlight-current-row @current-change="changeCurrentUser" @selection-change="handleSelectionChange" border>
            <el-table-column v-if="userData.type === 'copy' || userData.type === 'next'" width="55" type="selection" />
            <el-table-column v-else width="30">
              <template slot-scope="scope">
                <el-radio :label="scope.row.userId" v-model="currentUserId">{{ '' }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="用户昵称" align="center" prop="nickName" />
            <el-table-column label="在岗状态" align="center" key="workFlag" prop="workFlag" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.workFlag" size="medium" :type="workFlagType(scope.row.workFlag)">{{ workFlagText(scope.row.workFlag) }}</el-tag>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column label="手机" align="center" prop="phonenumber" />
            <el-table-column label="机构" align="center" prop="dept.deptName" />
          </el-table>
          <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userData.open = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { detailProcessNew, startSave } from '@/api/workflow/process'
import Parser from '@/utils/generator/parser'
import { complete, delegate, transfer, rejectTask, returnList, returnTask, instanceCancel, reqUpdateWorkStatus } from '@/api/workflow/task'
import { selectUser, deptTreeSelect } from '@/api/system/user'
import ProcessViewer from '@/components/ProcessViewer'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Treeselect from '@riophae/vue-treeselect'
import CptSelfForm from '@/components/CptSelfForm'
import { getConstForCurTaskOperateBtnConfig } from "@/utils/dict/cfg";
import taskDetail from "@/mixins/taskDetail"

export default {
  name: "WorkDetail",
  components: {
    ProcessViewer,
    Parser,
    Treeselect,
    CptSelfForm
  },
  mixins: [taskDetail],
  computed: {
    commentType() {
      return val => {
        switch (val) {
          case '1': return '通过'
          case '2': return '退回'
          case '3': return '拒绝'
          case '4': return '加签'
          case '5': return '转办'
          case '6': return '终止'
          case '7': return '撤回'
          case '8': return '撤销'
          // 被加签人审批通过
          case '9': return '通过'
        }
      }
    },
    approveTypeTag() {
      return val => {
        switch (val) {
          case '1': return 'success'
          case '2': return 'warning'
          case '3': return 'danger'
          case '4': return 'primary'
          case '5': return 'success'
          case '6': return 'danger'
          case '7': return 'info'
          case '8': return 'warning'
          case '9': return 'success'
        }
      }
    },
    workFlagText() {
      return val => {
        switch (val) {
          case '1': return '离岗'
          case '0': return '在岗'
        }
      }
    },
    workFlagType() {
      return val => {
        switch (val) {
          case '1': return 'warning'
          case '0': return 'success'
        }
      }
    }
  },
  data() {
    return {
      height: document.documentElement.clientHeight - 205 + 'px;',
      // 模型xml数据
      loadIndex: 0,
      xmlData: undefined,
      finishedInfo: {
        finishedSequenceFlowSet: [],
        finishedTaskSet: [],
        unfinishedTaskSet: [],
        rejectedTaskSet: []
      },
      historyProcNodeList: [],
      historyProcNodeListNew: [],
      // 机构名称
      deptName: undefined,
      // 机构树选项
      deptOptions: undefined,
      userLoading: false,
      // 用户表格数据
      userList: null,
      deptProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        deptId: undefined
      },
      activeLine: 1,
      total: 0,
      // 遮罩层
      loading: true,
      taskForm: {
        comment: "", // 意见内容
        procInsId: "", // 流程实例编号
        taskId: "",// 流程任务编号
        copyUserIds: "", // 抄送人Id
        vars: "",
        targetKey: ""
      },
      rules: {
        comment: [{ required: false, message: '请输入审批意见', trigger: 'blur' }],
      },
      currentUserId: null,
      variables: [], // 流程变量数据
      taskFormOpen: false,
      taskFormData: {}, // 流程变量数据
      processFormList: [], // 流程变量数据
      formOpen: false, // 是否加载流程变量数据
      returnTaskList: [],  // 回退列表数据
      processed: false,
      returnTitle: null,
      returnOpen: false,
      rejectOpen: false,
      rejectTitle: null,
      userData: {
        title: '',
        type: '',
        open: false,
      },
      copyUser: [],
      nextUser: [],
      userMultipleSelection: [],
      userDialogTitle: '',
      userOpen: false,
      curTaskOperateBtnConfig: getConstForCurTaskOperateBtnConfig()
    };
  },
  created() {
    console.log(this.$route);
    this.initData();
  },
  methods: {
    initData() {
      console.log(this.$route.params);
      console.log(this.$route.params.procInsId);
      this.taskForm.procInsId = this.$route.params && this.$route.params.procInsId;
      this.taskForm.taskId = this.$route.query && this.$route.query.taskId;
      this.processed = this.$route.query && eval(this.$route.query.processed || false);
      // 流程任务重获取变量表单
      this.getProcessDetails(this.taskForm.procInsId, this.taskForm.taskId, '2');
      //this.getProcessHis(this.taskForm.procInsId, this.taskForm.taskId);
      this.loadIndex = this.taskForm.procInsId;
    },
    /** 查询机构下拉树结构 */
    getTreeSelect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询用户列表 */
    getList() {
      this.userLoading = true;
      selectUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.toggleSelection(this.userMultipleSelection);
        this.userLoading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    handleUserQuery() {
      this.getList();
    },
    resetUserQuery() {
      if (this.$refs.tree) {
        this.$refs.tree.setCurrentKey(null);
      }
      this.resetForm("userQueryForm");
      this.queryParams.deptId = undefined;
      this.queryParams.nickName = undefined;
      this.getList();
    },
    setIcon(val) {
      if (val) {
        return "el-icon-check";
      } else {
        return "el-icon-time";
      }
    },
    apendStr(str1, str2) {
      if (!str1) {
        str1 = '';
      }
      if (!str2) {
        str2 = '';
      }
      return str1 + ' ' + str2;
    },
    setColor(val) {
      if (val) {
        return "#2bc418";
      } else {
        return "#b3bdbb";
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userMultipleSelection = selection
    },
    toggleSelection(selection) {
      if (selection && selection.length > 0) {
        this.$nextTick(() => {
          selection.forEach(item => {
            let row = this.userList.find(k => k.userId === item.userId);
            this.$refs.userTable.toggleRowSelection(row);
          })
        })
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    // 关闭标签
    handleClose(type, tag) {
      let userObj = this.userMultipleSelection.find(item => item.userId === tag.id);
      this.userMultipleSelection.splice(this.userMultipleSelection.indexOf(userObj), 1);
      if (type === 'copy') {
        this.copyUser = this.userMultipleSelection;
        // 设置抄送人ID
        if (this.copyUser && this.copyUser.length > 0) {
          const val = this.copyUser.map(item => item.id);
          this.taskForm.copyUserIds = val instanceof Array ? val.join(',') : val;
        } else {
          this.taskForm.copyUserIds = '';
        }
      } else if (type === 'next') {
        this.nextUser = this.userMultipleSelection;
        // 设置抄送人ID
        if (this.nextUser && this.nextUser.length > 0) {
          const val = this.nextUser.map(item => item.id);
          this.taskForm.nextUserIds = val instanceof Array ? val.join(',') : val;
        } else {
          this.taskForm.nextUserIds = '';
        }
      }
    },
    /** 流程变量赋值 */
    handleCheckChange(val) {
      if (val instanceof Array) {
        this.taskForm.values = {
          "approval": val.join(',')
        }
      } else {
        this.taskForm.values = {
          "approval": val
        }
      }
    },
    getProcessHis(procInsId, taskId) {
      console.log(procInsId, taskId);
      const params = { procInsId: procInsId, taskId: taskId }
      detailProcessNew(params).then(res => {
        const data = res.data;
        this.historyProcNodeListNew = data.historyProcNodeList;
      })
    },

    saveForm() {
      // 校验表单
      const taskFormRef = this.$refs.taskFormParser;
      const isExistTaskForm = taskFormRef !== undefined;
      // // 若无任务表单，则 taskFormPromise 为 true，即不需要校验
      // const taskFormPromise = !isExistTaskForm ? true : new Promise((resolve, reject) => {
      //   taskFormRef.$refs[taskFormRef.formConfCopy.formRef].validate(valid => {
      //     valid ? resolve() : reject()
      //   })
      // });
      // const approvalPromise = new Promise((resolve, reject) => {
      //   this.$refs['taskForm'].validate(valid => {
      //     valid ? resolve() : reject()
      //   })
      // });

      if (isExistTaskForm) {
        this.taskForm.variables = taskFormRef[taskFormRef.formConfCopy.formModel]
      }
      console.log("=====>>>" + this.taskForm)
      startSave(this.taskForm).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.goBack();
      });

    },
    onSelectCopyUsers() {
      this.userMultipleSelection = this.copyUser;
      this.onSelectUsers('添加抄送人', 'copy')
    },
    onSelectNextUsers() {
      this.userMultipleSelection = this.nextUser;
      this.onSelectUsers('指定审批人', 'next')
    },
    onSelectUsers(title, type) {
      this.userData.title = title;
      this.userData.type = type;
      this.getTreeSelect();
      this.getList()
      this.userData.open = true;
    },
    /** 通过任务 */
    handleComplete() {
      // 校验表单
      const taskFormRef = this.$refs.taskFormParser;
      const isExistTaskForm = taskFormRef !== undefined;
      // 若无任务表单，则 taskFormPromise 为 true，即不需要校验
      const taskFormPromise = !isExistTaskForm ? true : new Promise((resolve, reject) => {
        taskFormRef.$refs[taskFormRef.formConfCopy.formRef].validate(valid => {
          valid ? resolve() : reject()
        })
      });
      const approvalPromise = new Promise((resolve, reject) => {
        this.$refs['taskForm'].validate(valid => {
          valid ? resolve() : reject()
        })
      });
      Promise.all([taskFormPromise, approvalPromise]).then(() => {
        if (isExistTaskForm) {
          this.taskForm.variables = taskFormRef[taskFormRef.formConfCopy.formModel]
        }
        this.setTaskFormCommentDefault()
        complete(this.taskForm).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.goBack();
        });
      })
    },
    /** 委派任务 */
    handleDelegate() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          this.userData.type = 'delegate';
          this.userData.title = '委派任务'
          this.userData.open = true;
          this.getTreeSelect();
        }
      })
    },
    /** 转办任务 */
    handleTransfer() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          this.userData.type = 'transfer';
          this.userData.title = '转办任务';
          this.userData.open = true;
          this.getTreeSelect();
        }
      })
    },
    /** 拒绝任务 */
    handleReject() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          const _this = this;
          this.$modal.confirm('拒绝审批单流程会终止，是否继续？').then(function () {
            return rejectTask(_this.taskForm);
          }).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          });
        }
      });
    },
    /** 撤销任务 */
    handleCancel() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          const _this = this;
          this.$modal.confirm('撤销审批单流程会终止，是否继续？').then(function () {
            return instanceCancel(_this.taskForm);
          }).then(res => {
            reqUpdateWorkStatus(
              {
                businessKey: _this.$route.query['cur_businessKey'],
                businessStatus: "5",
                taskId: _this.taskForm.taskId,
              }
            ).then((res)=>{
              _this.$modal.msgSuccess(res.msg);
              _this.goBack();
            })
          });
        }
      });
    },
    changeCurrentUser(val) {
      this.currentUserId = val ? val.userId : null
    },
    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      this.$tab.closePage(this.$route)
      this.$router.back()
    },
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach(item => {
          let variableData = {};
          variableData.label = item.__config__.label
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach(val => {
              array.push(val)
            })
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue
          }
          variables.push(variableData)
        })
        this.variables = variables;
      }
    },
    submitUserData(checkType) {
      let type = this.userData.type;
      if (type === 'copy' || type === 'next') {
        if (!this.userMultipleSelection || this.userMultipleSelection.length <= 0) {
          this.$modal.msgError("请选择用户");
          return false;
        }
        let userIds = this.userMultipleSelection.map(k => k.userId);
        if (type === 'copy') {
          // 设置抄送人ID信息
          this.copyUser = this.userMultipleSelection;
          this.taskForm.copyUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
        } else if (type === 'next') {
          // 设置下一级审批人ID信息
          this.nextUser = this.userMultipleSelection;
          this.taskForm.nextUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
        }
        this.userData.open = false;
      } else {
        this.setTaskFormCommentDefault()
        if (!this.taskForm.comment) {
          this.$modal.msgError("请输入审批意见");
          return false;
        }
        if (!this.currentUserId) {
          this.$modal.msgError("请选择用户");
          return false;
        }
        if(this.userList) {
          let curUser = this.userList.find(v => { return  v.userId === this.currentUserId})
          if (curUser && curUser.workFlag === '1' && checkType !== '0') {
            const _this = this;
            this.$modal.confirm('该人员不在岗，确定指派任务嘛？').then(function () {
              return _this.submitUserData('0')
            }).then(res => {
            })
            return
          }
        }
        this.taskForm.userId = this.currentUserId;
        if (type === 'delegate') {
          const taskFormRef = this.$refs.taskFormParser;
          const isExistTaskForm = taskFormRef !== undefined;
          if (isExistTaskForm) {
            this.taskForm.variables = taskFormRef[taskFormRef.formConfCopy.formModel]
          }
          delegate(this.taskForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          });
        }
        if (type === 'transfer') {
          transfer(this.taskForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          });
        }
      }

    },
    /** 可退回任务列表 */
    handleReturn() {
      this.$refs['taskForm'].validate(valid => {
        if (valid) {
          this.returnTitle = "退回流程";
          returnList(this.taskForm).then(res => {
            this.returnTaskList = res.data;
            this.taskForm.values = null;
            this.returnOpen = true;
          })
        }
      });

    },
    /** 提交退回任务 */
    submitReturn() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          if (!this.taskForm.targetKey) {
            this.$modal.msgError("请选择退回节点！");
            return;
          }
          returnTask(this.taskForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack()
          });
        }
      });
    },
    getSelfFormData(fData) {
      return {
        'formContent': fData.formConfs,
        'formData': fData.variables,
        'optionData': {}
      }
    },
    isShowCommentInfo(comment) {
      // 特殊节点，特殊处理
      if (comment && comment.userId && comment.userId.length === 19 && Number.isInteger(Number(comment.userId))) {
        return false
      }
      return true
    },
    filterRepetitionCommentInfo(comments) {
      // 同一时间的回退任务comment，特殊处理
      const newCts = []
      for (const c of comments) {
        if (!newCts.some(nc => { return nc.time === c.time && nc.message === c.message })) {
          newCts.push(c)
        }
      }
      return newCts.slice().reverse()
    },
    setTaskFormCommentDefault() {
      if (this.taskForm && (this.taskForm.comment === null || this.taskForm.comment === undefined || this.taskForm.comment === '')) {
        this.taskForm.comment = '   '
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.button-new-tag {
  margin-left: 10px;
}

.card {
  border-color: #909399;
}
.card-header {
  font-size: 14px;
  font-weight: bold;
}

.operate-btn {
  width: 140px;
}

</style>
